/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.sunspotworld.sensortasks.routingtasks;

import com.sun.spot.peripheral.Spot;
import com.sun.spot.util.Utils;
import org.sunspotworld.sensortasks.SensorTask;
import org.sunspotworld.sensortasks.TimeKeeper;

/**
 *
 * @author me
 */
public class DataRoutingTask extends SensorTask {
    public static final long SLOT_SIZE = 500;
    public static final long INTER_SLOT_BUFFER = 3000;
    public static final byte OPEN = 0;
    public static final byte RECEIVE = 1;
    public static final byte BID = 2;
    public static final byte ADVERTISE = 3;
    public static final byte TRANSMIT = 4;
    public static final byte BUSY = 5;
    
    private SensorTask[] schedule;
    private byte[] states;
    
    public DataRoutingTask(int slots) {
        super.sampleInterval = slots*(SLOT_SIZE + INTER_SLOT_BUFFER);
        schedule = new SensorTask[slots];
        states = new byte[slots];
        schedule[0] = new AdvBidScheduleTask(SLOT_SIZE, this, 0);
    }
    
    private DataRoutingTask(long sample, long id, SensorTask[] sched, byte[] st) {
        super.sampleInterval = sample;
        super.id = id;
        schedule = sched;
        states = st;
    }
    
    protected SensorTask copy() {
        SensorTask task = (SensorTask)new DataRoutingTask(super.sampleInterval, super.id, schedule, states);
        task.setRepeat(super.repeating);
        return task;
    }
    
    protected void reportState(int slot, byte state) {
        states[slot] = state;
    }
    
    protected void scheduleAdvertise() {
        
    }
    
    protected void scheduleBid() {
        
    }
    
    public void runTask() {
        for (int i=0; i<schedule.length; i++) {
            long stop = TimeKeeper.getInstance().currentTimeMillis() + SLOT_SIZE + INTER_SLOT_BUFFER;
            if (schedule[i] != null) {
                schedule[i].runTask();
            } 
            if (stop > TimeKeeper.getInstance().currentTimeMillis()) {
                Utils.sleep(stop - TimeKeeper.getInstance().currentTimeMillis());
            }
        }
    }

}
